import { ref } from 'vue'
import { announcementApi } from '@/api/announcement'

export function useAnnouncements() {
  // 响应式数据
  const announcements = ref<any[]>([])
  const loading = ref(false)
  const error = ref('')
  const showAll = ref(false)
  
  // 方法
  const loadAnnouncements = async (page = 1, pageSize = 10) => {
    loading.value = true
    error.value = ''
    
    try {
      const response = await announcementApi.getAnnouncements({
        page,
        page_size: pageSize,
        active: true
      })
      
      // 兼容两种返回结构：ApiResponse 包裹 或 原始列表
      const list = (response as any)?.data?.announcements || (response as any)?.announcements || []
      announcements.value = Array.isArray(list) ? list : []
    } catch (err: any) {
      console.error('加载公告失败:', err)
      error.value = err?.message || '加载公告失败'
      announcements.value = []
    } finally {
      loading.value = false
    }
  }
  
  const refreshAnnouncements = () => {
    loadAnnouncements()
  }
  
  const toggleShowAll = () => {
    showAll.value = !showAll.value
  }
  
  const viewAnnouncementDetail = (announcement: any) => {
    console.log('查看公告详情:', announcement)
    // 这里可以实现跳转到详情页面或打开模态框
  }
  
  return {
    // 状态
    announcements,
    loading,
    error,
    showAll,
    
    // 方法
    loadAnnouncements,
    refreshAnnouncements,
    toggleShowAll,
    viewAnnouncementDetail
  }
}
